<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="80px"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" placeholder="请输入用户名" />
    </el-form-item>

    <el-form-item label="姓名" prop="realName">
      <el-input v-model="form.realName" placeholder="请输入姓名" />
    </el-form-item>

    <el-form-item label="手机号" prop="phone">
      <el-input v-model="form.phone" placeholder="请输入手机号" />
    </el-form-item>

    <el-form-item label="专长" prop="specialty">
      <el-input
        v-model="form.specialty"
        type="textarea"
        :rows="2"
        placeholder="请输入专长"
      />
    </el-form-item>


    <el-form-item>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getDepartmentList } from '@/api/department'

const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])

const formRef = ref()
const departments = ref([])
const form = ref({ ...props.modelValue })

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请选择科室', trigger: 'change' }
  ]
}

// 加载科室列表
const loadDepartments = async () => {
  try {
    const { data } = await getDepartmentList()
    console.log('-----科室列表' + data.records);
    departments.value = data.records;
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate()
  emit('submit', form.value)
}

onMounted(() => {
  loadDepartments()
})

// 监听表单数据变化
watch(
  () => props.modelValue,
  (val) => {
    form.value = { ...val }
  },
  { deep: true }
)
</script>
